package com.wutuo.contact.provider.component;


import cn.apestar.user.api.enums.UserType;
import cn.apestar.user.provider.info.domain.User;
import cn.apestar.user.provider.institution.domain.InstitutionSimpleVo;
import cn.apestar.util.CommonUtil;
import com.wutuo.child.api.response.ChildResponse;
import com.wutuo.contact.provider.vo.ContactListItem;
import com.wutuo.roster.api.response.ParentsResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class ContactDataConvert {

    public static List<ContactListItem> buildParentListResponse(List<ParentsResponse> parents,
        Map<Long, ChildResponse> childsInfoMap, Map<String, User> userInfoMap, Long currentUserId,
        InstitutionSimpleVo institutionSimpleVo) {

        if (CollectionUtils.isEmpty(parents)) {
            return Collections.emptyList();
        }

        List<ContactListItem> response = new ArrayList<>();
        for (ParentsResponse item : parents) {
            ContactListItem contactListItem = new ContactListItem();
            if (userInfoMap.get(item.getUserPhone()) == null) {
                continue; // v1.0.1 AA-133 如果用户已注册则不显示
            }

            // Wrap parent account info
            // if (StringUtils.isNotEmpty(item.getUserPhone()) &&
            // userInfoMap.get(item.getUserPhone()) != null) {
            if (StringUtils.isNotEmpty(item.getUserPhone())) {
                User user = userInfoMap.get(item.getUserPhone());
                if (user.getId().equals(currentUserId)) {
                    continue; // 联系人列表不返回自己，避免和自己对话
                }

                contactListItem.setImg(user.getPhoto());
                contactListItem.setSex(user.getSex());
                contactListItem.setRingId(user.getRingId());
            }
            ChildResponse child = childsInfoMap.get(item.getRosterId());
            contactListItem.setId(item.getId());
            contactListItem.setName(item.getUserName());
            contactListItem.setPhone(item.getUserPhone());
            contactListItem.setType(UserType.PARENT.getValue());
            contactListItem.setParentType(item.getUserTypeName());
            // Wrap child info
            if (item.getRosterId() != null && childsInfoMap.get(item.getRosterId()) != null) {
                contactListItem
                    .setYear(child.getYear() == null ? "" : String.valueOf(child.getYear()));
                contactListItem.setChildName(child.getName());
            }

            contactListItem.setInstitionInfo(institutionSimpleVo);

            response.add(contactListItem);
        }
        CommonUtil.sortDesc(response, "getYear");
        return response;
    }

}
